//
//  FileServiceManager.m
//  Common
//
//  Created by guoshiqing on 2018/5/31.
//

#import "FileManager.h"
#import <AFNetworking/AFNetworking.h>
#import "FileUtil.h"
#import "StringUtil.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface FileManager ()
@property (nonatomic, strong) AFHTTPSessionManager *manager;
@end

@implementation FileManager

- (instancetype)init {
    if (self = [super init]) {
    }
    return self;
}

+ (instancetype)shared {
    static FileManager *instance;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        instance = [[FileManager alloc] init];
    });
    
    return instance;
}

#pragma 注册返回
- (void)registerSaveSuccessBlock:(SaveFileSuccessBlock)saveFileSuccess
{
    _saveFileSuccess = saveFileSuccess;
}

// 根据类型获取对应字符串
- (NSString *)getAppModuleKeyByType:(EPModuleType)moduleType {
    return @"";
}

// 获取当前操作的企业名称
- (NSString *)getCurrentCompanyName
{
    return @"FiveStar";
}

// 文件存储目录：基础路径 / moduleCachePath / 模块名称(key)
- (NSString *)fileRootPathForAppModuleKey:(NSString *)key {
    NSString *fileRootPath = [self.moduleCachePath stringByAppendingPathComponent:key];
    if ([FileUtil isPathExist:fileRootPath] == NO) {
        [FileUtil createDir:fileRootPath];
    }
    return fileRootPath;
}

// 模块相关的缓存目录: 基础路径 / moduleCachePath
- (NSString *)moduleCachePath {
    NSString *cachePath = [self.baseCachePath stringByAppendingPathComponent:@"ModuleFilePath"];
    return cachePath;
}

// 基础缓存目录
- (NSString *)baseCachePath {
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    return (cachePath == nil)?@"":cachePath;
}

/////////////////////////////////////////////////////////////////////////////////

// 根据模块名称创建当前模块的缓存路径
+ (void)prepareFileManagerDirForAppModule:(EPModuleType)type {
    NSString *key = [FM getAppModuleKeyByType:type];
    NSString *fileRootPath = [FM fileRootPathForAppModuleKey:key];
    if ([FileUtil isPathExist:fileRootPath] == NO) {
        [FileUtil createDir:fileRootPath];
    }
}

// 清理缓存路径，并重新创建空目录
+ (void)clearCacheInFileManagerForAppModule:(EPModuleType)type {
    
    NSString *key = [FM getAppModuleKeyByType:type];
    if ([StringUtil isEmpty:key]) return;
    
    NSString *fileRootPath = [FM fileRootPathForAppModuleKey:key];
    [FileUtil removeSubDir:fileRootPath];
    
    //重建目录
    [self prepareFileManagerDirForAppModule:type];
}

// 获取模块的缓存路径
+ (NSString *)getFileRootPathForAppModule:(EPModuleType)type {
    NSString *key = [FM getAppModuleKeyByType:type];
    if ([StringUtil isEmpty:key]) return @"";
    return [FM fileRootPathForAppModuleKey:key];
}

/**
 * 云盘目录
 */
+ (NSString *)cloudStoragePath
{
    NSString *path = [self getFileRootPathForAppModule:@"test"];
    return path;
}

// 按照团队划分的云盘缓存 - 上传
+ (NSString *)cloudStoragePathAboutUpLoadingWithTeamId:(NSString *)TeamId
{
    NSString *path = [self.cloudStoragePath stringByAppendingPathComponent:TeamId];
    NSString *filePath = [path stringByAppendingPathComponent:@"UpLoading"];
    if ([FileUtil isPathExist:filePath] == NO) {
        [FileUtil createDir:filePath];
    }
    return filePath;
}

// 清理云盘上传文件
+ (void)clearCloudStoragePathAboutUpLoadingWithTeamId:(NSString *)TeamId
{
    NSString *fileRootPath = [self cloudStoragePathAboutUpLoadingWithTeamId:TeamId];
    [FileUtil removeSubDir:fileRootPath];
    
    //重建目录
    [FileUtil createDir:fileRootPath];
}

// 按照团队划分的云盘缓存 - 下载
+ (NSString *)cloudStoragePathAboutDownLoadWithTeamId:(NSString *)TeamId
{
    NSString *path = [self.cloudStoragePath stringByAppendingPathComponent:TeamId];
    NSString *filePath = [path stringByAppendingPathComponent:@"DownLoad"];
    if ([FileUtil isPathExist:filePath] == NO) {
        [FileUtil createDir:filePath];
    }
    return filePath;
}

// 清理云盘下载文件
+ (void)clearCloudStoragePathAboutDownLoadWithTeamId:(NSString *)TeamId
{
    NSString *fileRootPath = [self cloudStoragePathAboutDownLoadWithTeamId:TeamId];
    [FileUtil removeSubDir:fileRootPath];
    
    //重建目录
    [FileUtil createDir:fileRootPath];
}

// 查找云盘下载文件中是否已有该文件
+ (NSString *)searchCloudStoragePathAboutDownLoadWithTeamId:(NSString *)TeamId andFileName:(NSString *)FileName
{
    NSString *path = [self cloudStoragePathAboutDownLoadWithTeamId:TeamId];
    NSString *filePath = [path stringByAppendingPathComponent:FileName];
    if ([FileUtil isPathExist:filePath] == YES) {
        return filePath;
    }
    return @"";
}


/////////////////////////////////////////////////////////////////////////////////

+ (NSString *)saveCacheImage:(UIImage *)image fileName:(NSString *)fileName forAppModuleType:(EPModuleType)type {
    
    if ([StringUtil isEmpty:fileName]) return nil;
    
    NSString *imgHomeDir = [self getFileRootPathForAppModule:type];
    NSString *imgFilePath = [NSString stringWithFormat:@"%@/%@", imgHomeDir, fileName];
    
    //压缩图片： (此处不进行压缩，在第三方的选择图片那里选择压缩)
    NSData *data = [NSData data];
    if ([fileName containsString:@"PNG"]) {
        data = UIImagePNGRepresentation(image);
    } else {
        data = UIImageJPEGRepresentation(image, 1.0);
    }
    if ([data writeToFile:imgFilePath atomically:NO]) {
        return imgFilePath;
    }
    return nil;
}


/*
 存入云盘
 */
+ (NSString *)saveCacheImageToCloudDisk:(UIImage *)image fileName:(NSString *)fileName teamId:(NSString *)teamId {
    
    if ([StringUtil isEmpty:fileName]) return nil;
    
    NSString *imgHomeDir = [self cloudStoragePathAboutUpLoadingWithTeamId:teamId];
    NSString *imgFilePath = [NSString stringWithFormat:@"%@/%@", imgHomeDir, fileName];
    
    //压缩图片：
    NSData *data = [NSData data];
    if ([fileName containsString:@"PNG"]) {
        data = UIImagePNGRepresentation(image);
    } else {
        data = UIImageJPEGRepresentation(image, 1.0);
    }
    if ([data writeToFile:imgFilePath atomically:NO]) {
        return imgFilePath;
    }
    return nil;
}

+ (void)saveCacheVideoToCloudDisk:(NSURL *)videoUrl fileName:(NSString *)fileName teamId:(NSString *)teamId{
    
    if ([StringUtil isEmpty:fileName]) return;
    
    NSString *imgHomeDir = [self cloudStoragePathAboutUpLoadingWithTeamId:teamId];
    NSString *imgFilePath = [NSString stringWithFormat:@"%@/%@", imgHomeDir, fileName];
    
    if ([FileUtil isPathExist:imgFilePath] == YES) {
        [FM saveSuccessWithPath:imgFilePath];
        return;
    }
    
//    WEAKSELF
    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
//    __block BOOL SUCCESS = NO;
    [assetLibrary assetForURL:videoUrl resultBlock:^(ALAsset *asset) // substitute YOURURL with your url of video
     {
         ALAssetRepresentation *rep = [asset defaultRepresentation];
         Byte *buffer = (Byte*)malloc(rep.size);
         NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
         NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
         [data writeToFile:imgFilePath atomically:YES]; //you can remove this if only nsdata needed

         [FM saveSuccessWithPath:imgFilePath];
     }
     failureBlock:^(NSError *err) {
         NSLog(@"Error: %@",[err localizedDescription]);
     }];
}

- (void)saveSuccessWithPath:(NSString *)filePath
{
    if (self.saveFileSuccess) {
        self.saveFileSuccess(filePath);
    }
}

@end
